package com.example.swaggerDemo.controller;

import com.example.swaggerDemo.entity.MsgEntity;
import com.example.swaggerDemo.entity.OrderEntity;
import com.example.swaggerDemo.entity.SalaryEntity;
import com.example.swaggerDemo.entity.SysUserEntity;
import com.example.swaggerDemo.service.*;
import com.example.swaggerDemo.util.WXPayUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.Map;

import static com.example.swaggerDemo.util.SessionUtil.getIp;

@Api("订单支付服务")
@RestController
@RequestMapping(value="/wxpya")
public class WxpayController {
    @Autowired
    private WxpayService wxpay;
    @Autowired
    private orderService Service;
    @Autowired
    private PushService pushService;

    private final Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private SalaryService Salary;
    @Autowired
    private UserService SysUserDao;



    @ApiOperation(value="局部全套押金唤醒微信支付调用",notes="局部全套押金唤醒微信支付调用")
    @ResponseBody
    @RequestMapping(value="/WxpayByOredId",method= RequestMethod.POST)
    public MsgEntity WxpayByOredId(@RequestParam("OredId") String OredId,@RequestParam("notify_url") String notify_url) throws SQLException {
        String title = "微信支付订单";
        String remake = "";
        String openId = "";
        String ip = getIp();
        BigDecimal money = null;
        String wxordeid="";
        MsgEntity msg = new MsgEntity();
        OrderEntity dto = Service.findOredId(OredId);
        ModelAndView mv=new ModelAndView();
        if (dto != null) {
            SysUserEntity user = SysUserDao.findByid(dto.getUserid());
            //类型:0=测斑,1=局部,2=升级,3=全套,4=售后,5=代理
            if (dto.getTypedata().equals("1")) {

                title = "祛斑订单定金";
            }
            if (dto.getTypedata().equals("3")) {

                title = "签约订单定金";
                if (dto.getStatustype().equals(3)){
                    title = "签约尾款";
                }
            }
            if (dto.getTypedata().equals("5")) {
                title = "经纪人申请押金";
            }
            if(dto.getStatustype().equals("3")){
                money=dto.getTotalprice();
                 wxordeid= WXPayUtil.generateOrderId();//生成订单编号;
                Service.updatetailorde(OredId,wxordeid);
                System.out.println("生成订单编号："+wxordeid);
            }
            else {
                money=dto.getHetongmoney();
                wxordeid=dto.getWxordeid();
            }

            String fee=getMoney(money.toString());
            System.out.println("金额："+fee);

            msg=  wxpay.webPay(title,user.getOpenid(), ip,notify_url, fee.toString(),wxordeid);
        }
        return  msg;
    }


    @ApiOperation(value="订单升级支付",notes="订单升级支付")
    @ResponseBody
    @RequestMapping(value="/WxpayByOredIdUp",method= RequestMethod.POST)
    public MsgEntity WxpayByOredIdUp(@RequestParam("OredId") String OredId,@RequestParam("notify_url") String notify_url,@RequestParam("money") String money) throws SQLException {
        String title = "订单升级支付";
        String ip = getIp();
        String wxordeid="";
        MsgEntity msg = new MsgEntity();
        OrderEntity dto = Service.findOredId(OredId);
        ModelAndView mv=new ModelAndView();
        if (dto != null) {
            SysUserEntity user = SysUserDao.findByid(dto.getUserid());
                wxordeid= WXPayUtil.generateOrderId();//生成订单编号;
                Service.updauporde(OredId,wxordeid);
                System.out.println("生成订单编号："+wxordeid);
            String fee=getMoney(money);
            System.out.println("金额："+fee);
            msg=  wxpay.webPay(title,user.getOpenid(), ip,notify_url, fee.toString(),wxordeid);
        }
        return  msg;
    }


    @ApiOperation(value="微信签名分享",notes="微信签名分享")
    @ResponseBody
    @RequestMapping(value="/getWxConfig",method= RequestMethod.POST)
    public Map<String, String> getWxConfig(HttpServletRequest request, HttpServletResponse response){
        return  wxpay.getWxConfig(request, response);
    }

    /**
     * 元转换成分
     * @param amount
     * @return
     */
    public static String getMoney(String amount) {
        DecimalFormat df = new DecimalFormat("######0");
        Double d = Double.parseDouble(amount)*100;
        return df.format(d).toString();
    }


    @ApiOperation(value="微信支付回调",notes="微信支付回调")
    @ResponseBody
    @RequestMapping(value="/payCallback",method= RequestMethod.POST)
    public void callBack(HttpServletRequest request,HttpServletResponse response){
        System.out.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
        InputStream is = null;
        int k=0;
       String url="";
        try {
            is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = WXPayUtil.inputStream2String(is);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map
            System.out.println("微信支付成功notifyMap"+notifyMap);
            System.out.println("return_code"+notifyMap.get("return_code").equals("SUCCESS"));
            if(notifyMap.get("return_code").equals("SUCCESS")){
                    String ordersSn = notifyMap.get("out_trade_no");//商户订单号
                    String amountpaid = notifyMap.get("total_fee");//实际支付的订单金额:单位 分

                    System.out.println("准备修改订单状态："+ordersSn);
                    BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);//将分转换成元-实际支付金额:元

                        OrderEntity   order  =Service.findOredtailorde(ordersSn);

                    if(order != null) {
                        //pushService.pushPay(order.getUserid(),amountPay.toString(),ordersSn);
                        System.out.println("正在进入订单状态");
                        System.out.println("正在进入订单状态00:"+order.getStatustype()+"/000:"+order.getTypedata());
                        if (order.getTypedata().equals("1")&& order.getStatustype().equals("0")) {
                            System.out.println("正在进入修改局部支付待确认");
                         k=   Service.updateOrderType(order.getId().toString(), "1");
                        }
                        if (order.getTypedata().equals("3")&&order.getStatustype().equals("0")) {
                            System.out.println("正在进入修改签约支付待确认");
                            k=    Service.updateOrderType(order.getId().toString(), "1");
                        }
                        if (order.getTypedata().equals("3")&&order.getStatustype().equals("3")) {
                            System.out.println("正在进入修改签约已经支付尾款待完成·订单状态");
                            k=     Service.updateOrderType(order.getId().toString(), "2");
                        }
                        if (order.getTypedata().equals("5"))
                        {
                            System.out.println("正在进入修改押金订单状态");
                            k=     Service.updateOrderType(order.getId().toString(), "4");
                        }
                    }
                }
            if (k>0) {
                //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
                System.out.println("告诉微信服务器收到信息了，不要在调用回调action了");
                response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
                response.setContentType("text/xml");
                is.close();
            }
        } catch (Exception e) {
            System.out.println("错误.."+e.getMessage());
            e.printStackTrace();
        }

    }

    @ApiOperation(value="订单升级微信支付回调",notes="订单升级微信支付回调")
    @ResponseBody
    @RequestMapping(value="/payUpCallback",method= RequestMethod.POST)
    public void callUpBack(HttpServletRequest request,HttpServletResponse response){
        System.out.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
        InputStream is = null;
        int k=0;
        String url="";
        try {
            is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = WXPayUtil.inputStream2String(is);
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map
            System.out.println("微信支付成功notifyMap"+notifyMap);
            System.out.println("return_code"+notifyMap.get("return_code").equals("SUCCESS"));
            if(notifyMap.get("return_code").equals("SUCCESS")){
                String ordersSn = notifyMap.get("out_trade_no");//商户订单号
                //String amountpaid = notifyMap.get("total_fee");//实际支付的订单金额:单位 分

                System.out.println("准备修改订单状态："+ordersSn);
                //BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);//将分转换成元-实际支付金额:元

                OrderEntity    order  =Service.findOredUpId(ordersSn);

                if(order != null) {
                    System.out.println("正在进入订单状态");
                    pushService.pushUporader(order.getUserid(),"0");
                        System.out.println("正在进入修改押金订单状态");
                        k= Service.updaupordetpe(order.getId().toString());
                }
            }
            if (k>0) {
                //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
                System.out.println("告诉微信服务器收到信息了，不要在调用回调action了");
                response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
                is.close();
            }
        } catch (Exception e) {
            System.out.println("错误.."+e.getMessage());
            e.printStackTrace();
        }

    }

}
